<?php

/*
 *  menu callback : admin/systemreform/content
 */

function system_reform_content_overview() {
  module_load_include('inc', 'node', 'node.admin');
  if (isset($_POST['operation']) && $_POST['operation'] == 'delete') {
    return drupal_get_form('system_reform_node_multiple_delete_confirm', $_POST['nodes']);
  }
  $output = drupal_get_form('system_reform_filter_form', 'node', array('status' => 0, 'type' => 0, 'category' => 1), 'item');
  $output .= drupal_get_form('system_reform_node_admin_nodes');
  return $output;
}

/*
 *  构建过滤条件语句
 */

function system_reform_node_build_filter_query() {
  $where = $args = array();
  $join = '';
  $session = array();
  foreach ($_SESSION['system_reform_node_overview_filter'] as $key => $value) {
    if ($value != '')
      $session[] = array($key, $value);
  }
  foreach ($session as $index => $filter) {
    list($key, $value) = $filter;
    switch ($key) {
      case 'status':
        // Note: no exploitable hole as $key/$value have already been checked when submitted
        list($key, $value) = explode('-', $value, 2);
        $where[] = 'n.' . $key . ' = %d';
        break;
      case 'category':
        $table = "tn$index";
        $where[] = "$table.tid = %d";
        $join .= "INNER JOIN {term_node} $table ON n.nid = $table.nid ";
        break;
      case 'type':
        $where[] = "n.type = '%s'";
        break;
    }
    $args[] = $value;
  }
  $where = count($where) ? 'WHERE ' . implode(' AND ', $where) : '';

  return array('where' => $where, 'join' => $join, 'args' => $args);
}

/*
 *  记录筛选函数
 */

function system_reform_node_admin_nodes() {
  $filter = system_reform_node_build_filter_query();
  $result = pager_query(db_rewrite_sql('SELECT n.*, u.name FROM {node} n ' . $filter['join'] . ' INNER JOIN {users} u ON n.uid = u.uid ' . $filter['where'] . ' ORDER BY n.changed DESC'), 50, 0, NULL, $filter['args']);

  // Enable language column if locale is enabled or if we have any node with language
  $count = db_result(db_query("SELECT COUNT(*) FROM {node} n WHERE language != ''"));
  $multilanguage = (module_exists('locale') || $count);

  $form['options'] = array(
      '#type' => 'fieldset',
      '#title' => t('Update options'),
      '#prefix' => '<div class="container-inline">',
      '#suffix' => '</div>',
  );
  $options = array();
  foreach (module_invoke_all('node_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
  $options += array('categorize' => t('Add a term to selected nodes'), 'uncategorize' => t('Remove a term to selected nodes'));
  $form['options']['operation'] = array(
      '#type' => 'select',
      '#options' => $options,
      '#default_value' => 'approve',
  );

  $form['options']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Update'),
      '#submit' => array('node_admin_nodes_submit'),
  );
  /*  为nodes批量增加或者删除term功能  */
  $form['options']['operation']['#attributes']['onchange'] = 'system_reform_content_changed_operation(this)';
  $form['options']['terms-wrapper'] = array(
      '#type' => 'fieldset',
      '#attributes' => array('id' => 'edit-terms-wrapper', 'style' => 'display:none;'),
      'tid' => array(
          '#type' => 'select',
          '#title' => t("term"),
          '#options' => taxonomy_form_all(),
          '#theme' => 'taxonomy_term_select',
          '#description' => t("<p>Please select one term..</p>"),
      ),
  );
  drupal_add_js(drupal_add_js(drupal_get_path('module', 'system_reform') . '/system_reform.js'), 'inline');
  
  $languages = language_list();
  $destination = drupal_get_destination();
  $nodes = array();
  while ($node = db_fetch_object($result)) {
    $nodes[$node->nid] = '';
    $options = empty($node->language) ? array() : array('language' => $languages[$node->language]);
    $form['title'][$node->nid] = array('#value' => l($node->title, 'node/' . $node->nid, $options) . ' ' . theme('mark', node_mark($node->nid, $node->changed)));
    $form['name'][$node->nid] = array('#value' => check_plain(node_get_types('name', $node)));
    $form['username'][$node->nid] = array('#value' => theme('username', $node));
    $form['status'][$node->nid] = array('#value' => ($node->status ? t('published') : t('not published')));
    if ($multilanguage) {
      $form['language'][$node->nid] = array('#value' => empty($node->language) ? t('Language neutral') : t($languages[$node->language]->name));
    }
    $form['operations'][$node->nid] = array('#value' => l(t('edit'), 'node/' . $node->nid . '/edit', array('query' => $destination)));
  }
  $form['nodes'] = array('#type' => 'checkboxes', '#options' => $nodes);
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
  $form['#theme'] = 'node_admin_nodes';
  return $form;
}

function system_reform_node_admin_nodes_validate($form, &$form_state) {
  $nodes = array_filter($form_state['values']['nodes']);
  if (count($nodes) == 0) {
    form_set_error('', t('No items selected.'));
  }
}

function system_reform_content_operations_categorize($nids, $add = true) {
  $term = taxonomy_get_term($_POST['tid']);
  foreach ($nids as $nid) {
    if ($node = node_load($nid)) {
      $existing = taxonomy_node_get_terms($node);
      if ($add) {
        foreach ($existing as $k => $v) {
          if ($v->vid == $term->vid) unset($existing[$k]);//不允许一个node可以分到同一个vocabulary下的多个term
        }
        $existing[$_POST['tid']] = $term;
      }else {
        unset($existing[$_POST['tid']]);
      }
      taxonomy_node_save($node, $existing);
      drupal_set_message(t('Updated terms on node ' . l($node->title ? $node->title : $nid, "node/$nid")));
    }
  }
  cache_clear_all();
  drupal_set_message(t('Terms have been updated for the selected nodes.'));
}

/*
 *  删除node确认界面
 */

function system_reform_node_multiple_delete_confirm(&$form_state, $nodes) {
  $form['nodes'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  // array_filter returns only elements with TRUE values
  foreach ($nodes as $nid => $value) {
    $title = db_result(db_query('SELECT title FROM {node} WHERE nid = %d', $nid));
    $form['nodes'][$nid] = array(
        '#type' => 'hidden',
        '#value' => $nid,
        '#prefix' => '<li>',
        '#suffix' => check_plain($title) . "</li>\n",
    );
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
  $form['#submit'][] = 'system_reform_node_multiple_delete_confirm_submit';
  return confirm_form($form, t('Are you sure you want to delete these items?'), 'admin/systemreform/content', t('This action cannot be undone.'), t('Delete all'), t('Cancel'));
}

/*
 *  删除node
 */

function system_reform_node_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    foreach ($form_state['values']['nodes'] as $nid => $value) {
      node_delete($nid);
    }
    drupal_set_message(t('The items have been deleted.'));
  }
  $form_state['redirect'] = 'admin/systemreform/content';
  return;
}

?>